package com.itheima.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器类
 */


@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> doHandler(SQLIntegrityConstraintViolationException ex){
        log.error("异常信息："+ex.getMessage());//Duplicate entry 'zhangsan' for key 'idx_username'
        if(ex.getMessage().contains("Duplicate entry")){
            String msg = ex.getMessage().split(" ")[2]+"已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    /**
     * 异常处理方法
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> doHandler(CustomException ex){
        log.error("异常信息："+ex.getMessage());
        return R.error(ex.getMessage());
    }

}
